package cat.inkubator.plugin4j.updater;

import cat.inkubator.plugin4j.xml.Plugin;
import cat.inkubator.plugin4j.xml.Plugins;
import java.util.ArrayList;

/**
 *
 * @author gato
 */
public class PluginUpdater {
    
    private ArrayList<Plugin> download;
    private ArrayList<int[]> versionUpdate;

    public boolean update( Plugins pluginsLocal, Plugins pluginsWeb ){
        return this.checkNewVersions( pluginsWeb, pluginsLocal );
    }

    private boolean checkNewVersions( Plugins webPlugins, Plugins localPlugins ){
        ArrayList<Plugin> remote = webPlugins.getPlugins();
        ArrayList<Plugin> local = localPlugins.getPlugins();
        
        download = new ArrayList();
        versionUpdate = new ArrayList();

        int remoteSize = remote.size();
        int localSize = local.size();
        for( int i=0; i < remoteSize; i++ ){

            boolean exist = false;
            String artifact = remote.get(i).getArtifactId();
            String group = remote.get(i).getGroupId();
            
            for( int j=0; j < localSize; j++ ){
                if( local.get(j).getArtifactId().equalsIgnoreCase(artifact) &&
                        local.get(j).getGroupId().equalsIgnoreCase(group) ){

                    exist = true;
                    if( VersionChecker.check(local.get(j).getVersion(), remote.get(i).getVersion()) ){
                        getDownload().add( remote.get(i) );
                        int[] versions = { j, i };
                        this.getVersionUpdate().add(versions);
                        break;
                    }
                    
                }
            }

            if( !exist ){
                this.getDownload().add(remote.get(i));
                int[] versions = { -1, i };
                this.getVersionUpdate().add(versions);
            }
            
        }
        
        if( getDownload().size() > 0 ){
            return true;
        }else{
            return false;
        }
    }

    public ArrayList<Plugin> getDownload() {
        return download;
    }

    /**
     * @return the versionUpdate
     */
    public ArrayList<int[]> getVersionUpdate() {
        return versionUpdate;
    }

}
